package main

import (
	"image"
	"os"
)

const DefaultMapLength = 22
const DefaultMapWidth = 20

const DefaultErrorLogPath = "./errorLog.txt"

func main() {
	//运行GUI
	go func() {
		mw.Run()
		os.Exit(1)
	}()
	//获取难度等级

	//获取必要信息
	imageDefault:=ImageBasicInformation{
		length:    DefaultMapLength,
		width:     DefaultMapWidth,
		pixelPerL: 64,
		pixelPerW: 64,
		quality:   50,
	}
	//新建贪吃蛇地图
	var gsMap = new(GSMap)
	//初始化贪吃蛇地图
	err:=gsMap.Init(imageDefault.length,imageDefault.width)
	if err!=nil {
		ErrorCollector(DefaultErrorLogPath,err,"Map.Init执行失败")
	}
	//新建蛇
	var snake = new(Snake)
	//初始化蛇
	err=snake.Init(gsMap,"default")
	if err!=nil {
		ErrorCollector(DefaultErrorLogPath,err,"snake.Init执行失败")
	}
	//新建糖果
	var candy = new(Candy)
	//随机生成糖果
	err=candy.NewCandyRandomly(gsMap,snake)
	if err!=nil {
		ErrorCollector(DefaultErrorLogPath,err,"candy.NewCandyRandomly执行失败")
	}
	//清除屏幕,加入图形化界面后如果删除该函数程序运行不起来，原因不明
	ClearCmd()

	//
	backgroundData,err:=CreateBackground(imageDefault,"./pic/background.jpeg","./pic/yellowbarrier.jpeg")
	if err!=nil {
		ErrorCollector(DefaultErrorLogPath,err,"CreateBackground执行失败")
	}
	snakeBodyData,err:=OpenImageAndGetData("./pic/snakebody.jpeg",imageDefault)
	if err!=nil {
		ErrorCollector(DefaultErrorLogPath,err,"OpenImageAndGetData执行失败")
	}
	candyData,err:=OpenImageAndGetData("./pic/candy.jpeg",imageDefault)
	if err!=nil {
		ErrorCollector(DefaultErrorLogPath,err,"OpenImageAndGetData执行失败")
	}

	//此处开始运行
	//新建信号传输通道signalChan
	signalChan:=make(chan int)
	//该协程产生键盘信号或者超时信号放入signalChan，如果函数执行失败会panic
	go ScanSingleKey(signalChan,snake)
	//接收键盘信号或者超时信号，做出响应变化，画出新地图
	for instruction:=range signalChan {
		snake.SnakeHeadStretch(instruction)
		collide,err:=snake.IfSnakeCollide(gsMap)
		if err!=nil {
			ErrorCollector(DefaultErrorLogPath,err,"snake.IfSnakeCollide执行失败")
		}
		if collide {
			return
		}
		eaten:=snake.IfSnakeEatCandy(candy)
		if !eaten {
			err=snake.RemoveTail()
			if err!=nil {
				ErrorCollector(DefaultErrorLogPath,err,"snake.IfSnakeEatCandy执行失败")
			}
		} else {
			err=candy.NewCandyRandomly(gsMap,snake)
			if err!=nil {
				ErrorCollector(DefaultErrorLogPath,err,"candy.NewCandyRandomly执行失败")
			}
		}
		//ok
		//将糖果和蛇画入照片
		//深拷贝
		backgroundDataCopy:=new(image.NRGBA)
		backgroundDataCopy.Rect=backgroundData.Rect
		backgroundDataCopy.Stride=backgroundData.Stride
		sli:=make([]uint8,len(backgroundData.Pix))
		copy(sli,backgroundData.Pix)
		backgroundDataCopy.Pix=sli
		err=RenderCandyAndSnake("./pic/picToShow.jpeg",candy,snake,backgroundDataCopy,candyData,snakeBodyData,&imageDefault)
		if err != nil {
			ErrorCollector(DefaultErrorLogPath,err,"RenderCandyAndSnake执行失败")
		}
		ImageReadyToShow<- struct{}{}
		<-ImageFinishShowing
	}
}
